<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class GCMUsers extends MY_Controller {

	function __construct() {

		parent::__construct();
		$this->load->model('GCMModel');
		$this->load->model('T_chat');
	}

	public function index()
	{	
		$data = array();
		$data['resultUsers'] = $this->GCMModel->getAllUsers();
		$NumOfUsers = sizeof($data['resultUsers']);
		$data['num'] = $NumOfUsers;
		$this->load->view('list_user' , $data);
	}

	/**
	 * Logout : change activate field to 0
	 */
	public function logout(){
		//get data post
		$post = $this->input->post();
		//check value post if !=null continue else return false
		$post = parent::check_post_value($post);
		
		$gcm_array = array();
		
		if(isset($post[GCM_REGID])){
			$gcm_array[GCM_REGID] = $post[GCM_REGID];
		}else{
			parent::print_result( 'token is null' , 0 );
			exit();
		}

		$gcm_array[GCM_ACTIVE] = 0;
		$gcm_array[LOGIN_IS_ACTIVITY] = 0;
		$result = $this->GCMModel->updateInfoUserGCM($gcm_array);

		if($result >0){
			parent::print_result( 'logout success' , 1 );
		}else{
			parent::print_result( 'logout failed , try again late' , 0 );
		}
	}

	/**
	 * Register with gcm server
	 */
	public function register_gcm(){

		//get data post
		$post = $this->input->post();
		if(empty($post)){
			return parent::print_result('Missing post');exit();
		}
		if(!isset($post[DATA])){
			return parent::print_result('Missing key or value data');exit();	
		}
		// get data post
		$post = (array) json_decode($post[DATA],true);
		$gcm_array = array();
		// message return if success
		$message = 'register success!!!';
		
		if(isset($post[GCM_REGID])){
			$gcm_array[GCM_REGID] = $post[GCM_REGID];
		}else{
			parent::print_result( 'token is null' , 0 );
			exit();
		}

		if(isset($post[DEVICE_ID])){
			$deviceId = $post[DEVICE_ID];
			$gcm_array[DEVICE_ID] = $post[DEVICE_ID];
		}else{
			parent::print_result( DEVICE_ID .' is null' , 0 );
			exit();
		}

		if(isset($post[USER_ID])){
			$gcm_array[USER_ID] = $post[USER_ID];
			$from = $post[USER_ID];
		}else{
			$from = -1;
		}

		if(isset($post[GCM_TYPE])){
			$gcm_array[GCM_TYPE] = $post[GCM_TYPE];
		}else{
			parent::print_result('device type unknown' , 0 );
			exit();
		}
		$gcm_array[GCM_ACTIVE] = 1;
		$gcm_array[LOGIN_USER_ID] = 0;

		$count = $this->GCMModel->checkDeviceId($deviceId);

		if($count <= 0){
			$result = $this->GCMModel->storeUserGCM($gcm_array);

			if( $result > 0){
				$result = $this->send_notification_android(array($gcm_array[GCM_REGID]) , $this->generate_message_gcm($message , 1 , $from, $from));
				$result = json_decode($result, true);
				parent::print_result($result, SUCCESS_VALUE);
			}else{
				parent::print_result('insert sida cmnr' , 0 );	
				exit();
			}	
		}else{
			$where = array(DEVICE_ID=>$gcm_array[DEVICE_ID]);
			// unset($gcm_array[DEVICE_ID]);

			$result = $this->GCMModel->update_infor_gcm_by_property($gcm_array , $where);
			if(!empty($result)){
				$result = $this->send_notification_android(array($gcm_array[GCM_REGID]) , $this->generate_message_gcm($message , 1 , $from, $from));
				$result = json_decode($result, true);
				parent::print_result($result, SUCCESS_VALUE);
			}else{
				parent::print_result('insert sida cmnr existed' , SUCCESS_VALUE );	
				exit();
			}	
		}
		

	}

	/**
	 * check user id is register gcm with server
	 * @return boolean [description]
	 */
	public function is_register(){
		$post = $this->input->post();
		try{
			$post = json_decode($post[DATA], true);
		}catch(Exception $e){
			parent::print_result(array(DATA => 0));exit();
		}
		

		if(isset($post[GCM_REGID])){
			$gcm_regid = $post[GCM_REGID];
		}else{
			parent::print_result(array( GCM_REGID => 0));exit();
		}

		if(isset($post[USER_ID])){
			$user_id = $post[USER_ID];
		}else{
			parent::print_result(array( USER_ID => 0));exit();
		}

		$query = $this->GCMModel->get_data_by_property(array(GCM_REGID => $gcm_regid));
		if(!empty($query) && count($query) > 0){
			foreach ($query as $key => $value) {
				if($value[LOGIN_USER_ID] == $user_id){
					// đã login
					parent::print_result(1, SUCCESS_VALUE);exit();
				}
			}
			// đã đăng ký gcm but chưa login
			parent::print_result(-1, SUCCESS_VALUE);exit();
		}else{
			// chưa đăng ký gì cả
			parent::print_result(0, SUCCESS_VALUE);exit();
		}
	}

	/**
     * Sending Push Notification
     */
    public function send_notification_android($regArray , $msg , $type = 3 , $id_go_to = -1) {

		$message = array("price" => $msg , "type" => $type , "id_go_to"=>$id_go_to);
		// $regArray[]=$registatoin_ids;
        // Set POST variables
        $url = 'https://android.googleapis.com/gcm/send';
        $fields = array(
            'registration_ids' => $regArray,
            'data' => $message,
        );

        $headers = array(
            'Authorization: key=' . GOOGLE_API_KEY,
            'Content-Type: application/json'
        );
        // Open connection
        $ch = curl_init();

        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }

        // Close connection
        curl_close($ch);
        // echo $result;
        return $result;
    }

    /**
     * Send notificate to a device android
     */
    public function send_notification_a_devices_android($regId , $msg){
    	$this->send_notification_android(array($regId) , $msg);
    }

    /**
     * submit chat & send chat
     */
    public function submit_chat(){
    	//get data post
		$post = $this->input->post();
		//check value post if !=null continue else return false
		parent::check_post_value($post);
		// get data post
		$post = (array) json_decode($post[DATA]);

		if(isset($post[GCM_REGID])){
			$gcm_array[GCM_REGID] = $post[GCM_REGID];
		}else{
			parent::print_result( 'token is null');
			exit();
		}

		if(isset($post[MESSAGE]) && strlen($post[MESSAGE]) > 0 ){
			$gcm_array[MESSAGE] = $post[MESSAGE];
		}else{
			parent::print_result( 'Key or value message is null' );
			exit();
		}

		if(isset($post[CHAT_TO]) && strlen($post[CHAT_TO]) > 0 ){
			$gcm_array[CHAT_TO] = $post[CHAT_TO];
		}else{
			parent::print_result( 'not user address to send');
			exit();
		}

		$message = $post[MESSAGE];
		$regId = $post[GCM_REGID];
		$to_user_id = $post[CHAT_TO];
		$arr_gcm = $this->GCMModel->getGCMUsers(array( GCM_REGID => $regId ));
		if(count($arr_gcm) > 0){
			$user_post_id = $arr_gcm[0][USER_ID];
			$fromUserName = $arr_gcm[0][USER_NAME];

			$this->load->model('t_user');
			$userTo = $this->t_user->get_data_by_id($to_user_id);
			$toUserName = $userTo[0][USER_NAME];
		}else{
			parent::print_result('user from gcmId unregister', 0);
		}

		$arrFromRegId = $this->GCMModel->getRegIdListFromUserId($user_post_id , $regId);
		$arrFromChatTo = $this->GCMModel->getRegIdListFromUserId($to_user_id);
		if(empty($arrFromChatTo)){
			parent::print_result('user to gcm_regid unregister');
		}
		$arrMerge = array_merge($arrFromRegId , $arrFromChatTo);
		$result_send = $this-> send_notification_android ($arrMerge , $this->generate_message_gcm( $message , 3 , $user_post_id , $to_user_id, $fromUserName, $toUserName));
		$result_send = json_decode($result_send, true);
		if(isset($result_send[SUCCESS]) && $result_send[SUCCESS] >= 1){

			$data = array();
			$data[CHAT_FROM] = $user_post_id;
			$data[CHAT_TO] = $to_user_id;
			$data[CHAT_CONTENT] = $message;
			$data[CHAT_TYPE] = 3;
			$data[CHAT_FROM_NAME] = $fromUserName;
			$data[CHAT_TO_NAME] = $toUserName;
			$data['result_send'] = $result_send;
			parent::print_result($data, SUCCESS_VALUE);
		}
		exit();
    }

    /**
     * Generate json result of push notification
     */
    public function generate_message_gcm($message , $type , $from = -1 , $to = -1,$fromUserName = '', $toUserName = '' , $user_receive_message_id = -1){

    	$data = array();
		$data[CHAT_FROM] = $from;
		$data[CHAT_TO] = $to;
		$data[CHAT_CONTENT] = $message;
		$data[CHAT_TYPE] = $type;
		$data[CHAT_USER_RECEIVE_MESSAGE_ID] = $user_receive_message_id;

		$idSave = $this->T_chat->set_data($data);

    	$mess_array = array( CHAT_ID=> $idSave , CHAT_USER_RECEIVE_MESSAGE_ID=> $user_receive_message_id, CHAT_TYPE => $type, CHAT_CONTENT => $message , CHAT_FROM => $from , CHAT_TO => $to, CHAT_FROM_NAME => $fromUserName,CHAT_TO_NAME =>$toUserName );

    	return json_encode($mess_array)	;
    }

    /**
     * disconnect all user
     */
    public function disconnect_when_have_change(){
    	//get data post
		$post = $this->input->post();
		//check value post if !=null continue else return false
		parent::check_post_value($post);
		// get data post
		$post = (array) json_decode($post[DATA]);

		if(isset($post[GCM_REGID])){
			$gcm_array[GCM_REGID] = $post[GCM_REGID];
		}else{
			parent::print_result( 'token is null' , 0 );
			exit();
		}

		$regId = $post[GCM_REGID];

		$arr_gcm = $this->GCMModel->getGCMUsers(array( GCM_REGID => $regId ));
		if(count($arr_gcm) > 0){
			$user_post_id = $arr_gcm[0][USER_ID];
		}

		$arrFromRegId = $this->GCMModel->getRegIdListFromUserId($user_post_id , $regId);

		$result_send = $this-> send_notification_android ($arrMerge , $this->generate_message_gcm( 'disconnectted by user' , 0 ) );

    }

    /**
     * Push new banner
     */
    public function create_new_adversting(){
		
    	$arr_adversting_image = array('http://xn--gchun-4ya0514cqjaib.vn/upload/Colombo/23100/20130621/banner.jpg' , 
    		'http://farm6.staticflickr.com/5327/7440762638_383e3d7c4b_b.jpg',
    		'http://phunudanang.org.vn/images/system/banner5.png',
    		);

    	$arr_adversting_link = array('http://xn--gchun-4ya0514cqjaib.vn/upload/Colombo/23100/20130621/banner.jpg' , 
    		'http://farm6.staticflickr.com/5327/7440762638_383e3d7c4b_b.jpg',
    		'http://phunudanang.org.vn/images/system/banner5.png',
    		);

    	$array_result = array();
    	for($i = 0 ; $i < count($arr_adversting_image) ; $i++){
    		$array_result[$i] = array();
    		$array_result[$i]['image'] = $arr_adversting_image[$i];
    		$array_result[$i]['link'] = $arr_adversting_link[$i];
    	}

    	$list_push = $this->GCMModel->getListGcmActivatedAndroid();
    	$list_id_pust = array();
    	for($i = 0 ; $i < count($list_push) ; $i ++){
    		$list_id_pust[$i] = $list_push[$i][GCM_REGID];
    	}
    	echo $this->send_notification_android($list_id_pust , json_encode($array_result) , -1 );
    }

    public function get_link_banner_adversting(){
    	$arr_adversting_image = array('http://xn--gchun-4ya0514cqjaib.vn/upload/Colombo/23100/20130621/banner.jpg' , 
    		'http://farm6.staticflickr.com/5327/7440762638_383e3d7c4b_b.jpg',
    		'http://phunudanang.org.vn/images/system/banner5.png',
    		);

    	$arr_adversting_link = array('http://xn--gchun-4ya0514cqjaib.vn/upload/Colombo/23100/20130621/banner.jpg' , 
    		'http://farm6.staticflickr.com/5327/7440762638_383e3d7c4b_b.jpg',
    		'http://phunudanang.org.vn/images/system/banner5.png',
    		);
    	$array_result = array();
    	for($i = 0 ; $i < count($arr_adversting_image) ; $i++){
    		$array_result[$i] = array();
    		$array_result[$i]['image'] = $arr_adversting_image[$i];
    		$array_result[$i]['link'] = $arr_adversting_link[$i];
    	}

    	parent::print_result($array_result , 1);

    }


}